<!--
 * @Description: 选择餐厅
 * @Author: Kerwin
 * @Date: 2025-04-29 14:04:33
 * @LastEditTime: 2025-11-20 11:40:27
 * @LastEditors:  Please set LastEditors
-->

<template>
  <view class="chooseShop">
    <view class="header">
      <searchBar
        :address="WZAdress"
        @on-search="onSearch"
        @onAddressChange="handleAddressChange"
      />
    </view>
    <view class="footer">
      <view class="shop">
        <text style="font-size: 32rpx"
          >{{ brandName ? `${brandName}-` : '' }}附近餐厅</text
        >
        <text @click="onClickRight">
          <van-icon style="color: #2e2e2e" size="18" name="replay"
        /></text>
      </view>
      <view>
        <C_SHOP
          v-if="WZAdress"
          :address="WZAdress"
          :brandId="brandId"
          :searchShopName="searchShopName"
          :isApp="isApp"
          :refresh="refresh"
        >
        </C_SHOP>
        <view v-else>正在加载附近餐厅...</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { watch, ref, reactive } from 'vue'
import {
  onReady,
  onShow,
  onLoad,
  onReachBottom,
  onPageScroll,
  onShareAppMessage,
  onPullDownRefresh
} from '@dcloudio/uni-app'
//#region ************ api ********************** */
import { baseApi, moneyApi, userApi, productApi } from '@/api'
//#region ************ 引入组件 ********************** */
//搜索
import searchBar from '@/components/hy-search-bar3/index.vue'
//附近
import C_SHOP from './c_shop.vue'
//工具
import { getWZLocation } from '@/utils'
import { getLocationInfo } from '@/utils/location'
import { useShopInfoStore, useCartStore } from '@/store'
//#endregion

//#region ************ 初始数据 ********************** */
const carStore = useCartStore()
const shopStore = useShopInfoStore()
const adress = ref()
const WZAdress = ref()
const brandId = ref()
const searchShopName = ref()
const isApp = ref(false) //p判断是否是app进入
const refresh = ref(false) //p判断是否刷新
const brandName = ref('')
const appLocation = ref({})
const shopTypeAllList = ref([
  { name: '黑银', id: 0 },
  { name: '花积分', id: 1 },
  { name: '链动模式', id: 2 },
  { name: '酒慕网', id: 3 },
  { name: '鑫复来', id: 4 },
  { name: '长来科技', id: 6 }
])
const shopMode = ref(4)
//#endregion

//#region ************ 搜索 ********************** */
const onSearch = (value: any) => {
  searchShopName.value = value
}
//#endregion

//监听adress
watch(
  () => adress,
  async (newId, oldId) => {}
)
watch(
  () => brandId.value,
  async (newId, oldId) => {
    switch (newId) {
      case '1':
        brandName.value = '肯德基'
        break
      case '13':
        brandName.value = '瑞幸咖啡'
        break
      case '10':
        brandName.value = '星巴克'
        break
      case '19':
        brandName.value = '喜茶'
        break
      case '2':
        brandName.value = '奈雪'
        break
      case '5':
        brandName.value = '麦当劳'
        break

      default:
        break
    }
  }
)

//用户信息获取location
const userLocation = async () => {
  const { data } = await userApi.userInfo()
  return { latitude: data.latitude, longitude: data.longitude }
}

//定位逆解析
const getAddress = async (address: any) => {
  uni.setStorageSync('wzLocation', address)
  const { data } = await baseApi.reverseGeocoding(address)
  if (data) {
    WZAdress.value = data
    uni.setStorageSync('wzLocation', data)
  }
}

//刷新
const onClickRight = () => {
  refresh.value = true
  if (isApp.value) {
    uni.redirectTo({
      url: `/pages/bigLife/chooseShop?brandId=${brandId.value}&from=app&mode=${shopMode.value}`
    })
  } else {
    uni.redirectTo({
      url: `/pages/bigLife/chooseShop?brandId=${brandId.value}&from=h5&mode=${shopMode.value}`
    })
  }
}

// 封装定位获取逻辑，支持 fallback
const getLocationWithFallback = async () => {
  try {
    return await getWZLocation()
  } catch (err) {
    console.warn('getWZLocation 失败，尝试兜底方案')
    return {
      latitude: 30.672477,
      longitude: 104.066534
    } // 默认成都坐标兜底
  }
}

const handleAddressChange = (addressData: any) => {
  // 在这里处理地址数据
  WZAdress.value = addressData
}

onShow(() => {
  adress.value = uni.getStorageSync('currentAddress')
  carStore.clearGoods() // 直接调用 store 方法清空
})

// 只有这个页面的所有组件都是获取的url的mode字段
onLoad(async (option: any) => {
  console.log('option', option)
  shopMode.value = option?.mode || 4
  brandId.value = option.brandId
  let location = null
  // app/ios
  if (option?.from && option.from.toLowerCase() === 'app') {
    isApp.value = true
    shopStore.setIsApp(isApp.value)
    uni.setStorageSync('from', isApp.value)
    // #ifdef H5
    // @ts-ignore
    window.JSBridge.registerEvent('HYUserEvent', async (data) => {
      console.log('收到 App 用户信息:', data)
      const result = await getLocationInfo()
      location = result.location
      WZAdress.value = result.address
    })
    // #endif
  } else {
    //h5
    const result = await getLocationInfo()

    location = result.location
    WZAdress.value = result.address
  }

  // 安全地处理 mode 参数
  if (option?.mode) {
    try {
      const modeArr = shopTypeAllList.value.filter(
        (item) => item.id == option.mode
      )
      // 确保存储的是有效的 JSON 字符串
      uni.setStorageSync('hyType', JSON.stringify(modeArr[0]))
      uni.setStorageSync('shopMode', option?.mode)
    } catch (e) {
      console.error('序列化 hyType 失败:', e)
    }
  } else {
    // 确保存储的是有效的 JSON 字符串
    uni.setStorageSync('hyType', JSON.stringify(shopTypeAllList.value[4]))
    uni.setStorageSync('shopMode', 4)
  }
})
</script>

<style lang="scss" scoped>
.chooseShop {
  padding: 0 20rpx;

  .header {
    box-sizing: border-box;
    margin-top: 100rpx;
  }
}
.footer {
  margin-top: 200rpx;
}

.shop {
  margin-bottom: 20rpx;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
